import store from "@/store/index.js";
const baseUrl = "https://hzlaba.top/prod-api/";

const httpInterceptor = {
  invoke(args) {
    // 拦截前触发,拼接url
    if (!args.url.startsWith("http")) {
      args.url = baseUrl + args.url;
    }

    //请求超时时间，默认60s
    args.timeout = 10000;

    //添加小程序请求头标志
    args.header = {
      ...args.header,
      "source-client": "miniapp",
    };

    //添加token
    const token = uni.getStorageSync("token");
    const clientId = uni.getStorageSync("clientId");
    if (token) {
      args.header.Authorization = "Bearer " + token;
      args.header.tenantId = "000000";
      args.header.clientId = clientId;
    }
  },
};

// 添加拦截器
uni.addInterceptor("request", httpInterceptor);
uni.addInterceptor("uploadFile", httpInterceptor);

//定义泛型，接口返回的数据结构
const http = (options) => {
  return new Promise((resolve, reject) => {
    uni.request({
      ...options,
      // 响应成功
      success(res) {
        // 判断状态码
        if (res.data.code === 200) {
          resolve(res.data); // 返回接口返回的数据
        } else if (res.data.code === 401) {
          uni.removeStorageSync('token');
          uni.removeStorageSync('clientId');
          uni.removeStorageSync('userInfo');
        } else {
          reject(new Error(`请求失败，状态码：${res.data.code}`));
        }
      },
      fail(err) {
        // 响应失败，网络错误，调用reject
        uni.showToast({
          title: "网络错误，换个网络试试",
          icon: "none",
        });
        reject(err);
      },
    });
  });
};

export default http;
